package com.example.demo.interceptor;

import com.example.demo.common.Result;
import com.example.demo.util.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ObjectMapper objectMapper;

    private static final String TOKEN_PREFIX = "user:token:";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        // 放行登录和登出接口
        if (requestURI.contains("/api/user/login") || requestURI.contains("/api/user/logout")) {
            return true;
        }
        // 获取请求头中的token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            handleUnauthorized(response, "未提供token");
            return false;
        }
        // 从Redis中获取用户信息，验证token
        String redisKey = TOKEN_PREFIX + token;
        Object user = redisUtil.get(redisKey);
        if (user == null) {
            handleUnauthorized(response, "token无效或已过期");
            return false;
        }
        return true;
    }

    private void handleUnauthorized(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write(objectMapper.writeValueAsString(Result.businessError(message)));
    }
} 